package com.ibuonline.b2b.common.tag;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspException;

import com.ibuonline.b2b.common.SysCache;
import com.ibuonline.b2b.entity.BaseOption;

public class BaseOptionRadioBoxTag extends BaseCustomerTag {

	private static final long serialVersionUID = 8248756476934340948L;
	private String name;
	private String type;
	
	public int doStartTag() throws JspException {
		StringBuilder sb = new StringBuilder();
		List<BaseOption> baseOptions = SysCache.getOptionByType(type);
		String paramValue = pageContext.getRequest().getAttribute(name)+"";
		
		// when default value is null, assign the first option's value to defaultValue, 
		// so that the first option is checked. Added by Linyufa (2011-12-30)
		if (defaultValue == null && baseOptions.size() > 0)
			defaultValue = baseOptions.get(0).getOptionValue();
		for(BaseOption option : baseOptions) {
			String id = type + "_" + option.getOptionValue();
			sb.append(" <input type='radio' name='").append(name)
				.append("' id='").append(id)
				.append("' value='").append(option.getOptionValue()).append("'");
			if (!paramValue.equals("null")) {
				if (paramValue.equals(option.getOptionValue())) {
					sb.append(" checked='checked' ");
				}
			} else if (option.getOptionValue().equals(defaultValue)) {
				// when action didn't pass values to the JSP and current option value 
				// equals default value, let current option checked. Added by LinYufa (2011-12-30)
				sb.append(" checked='checked' ");
			}
			
			generateAttribute(sb);
			sb.append(" /> ").append("<label for='").append(id).append("'>")
			.append(option.getOptionName()).append("</label> &nbsp;\n");
		}
		try {
			pageContext.getOut().print(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_BODY_INCLUDE;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}
